
#include "TableAlgebra.h"
#include <assert.h>

using namespace std;

TableAlgebra::TableAlgebra() :
	IAlgebra(),
	m_Length(0),
	m_MultiplicationTable(0),
	m_AdditionTable(0)
{
}

TableAlgebra::TableAlgebra(WORD n, BYTE** addition_table, BYTE** multiplication_table)
{
	Set(n, addition_table, multiplication_table);
}

TableAlgebra::TableAlgebra(const TableAlgebra &other)
{
	SetFromOther(other);
}

//void TableAlgebra::operator = (const TableAlgebra &other)
//{
//	if(this == &other)
//	{
//		return;
//	}
//	UnSet();
//	SetFromOther(static_cast<const TableAlgebra>(other));
//}

TableAlgebra::~TableAlgebra()
{
	UnSet();
}

void TableAlgebra::SetFromOther (const TableAlgebra &other)
{
	BYTE** addition_table = static_cast<const TableAlgebra>(other).m_AdditionTable;
	BYTE** multiplication_table = static_cast<const TableAlgebra>(other).m_MultiplicationTable;
	m_Length = other.m_Length;
	m_ZeroElement = other.m_ZeroElement;
	m_UnityElement = other.m_UnityElement;
	m_MultiplicationTable = new BYTE*[m_Length];
	m_AdditionTable = new BYTE*[m_Length];
	for(size_t i = 0; i < m_Length; i++)
	{
		m_MultiplicationTable[i] = new BYTE[m_Length];
		m_AdditionTable[i] = new BYTE[m_Length];
		for(size_t j = 0; j < m_Length; j++)
		{
			m_MultiplicationTable[i][j] = multiplication_table[i][j];
			m_AdditionTable[i][j] = addition_table[i][j];
		}
	}
}

void TableAlgebra::Set(WORD n, BYTE** addition_table, BYTE** multiplication_table)
{
	m_Length = n;
	m_MultiplicationTable = multiplication_table;
	m_AdditionTable = addition_table;
	for(size_t i = 0; i < m_Length; i++)
	{
		bool is_unity = true;
		bool is_zero = true;
		for(size_t j = 0; j < m_Length; j++)
		{
			if(addition_table[i][j] != j)
			{
				is_zero = false;
			}
			if(multiplication_table[i][j] != j)
			{
				is_unity = false;
			}
		}
		if(is_unity)
		{
			m_UnityElement = i;
		}
		if(is_zero)
		{
			m_ZeroElement = i;
		}
	}
}

void TableAlgebra::UnSet()
{
	for(size_t i = 0; i < m_Length; i++)
	{
		delete[] m_MultiplicationTable[i];
		delete[] m_AdditionTable[i];
	}
	delete[] m_MultiplicationTable;
	delete[] m_AdditionTable;
}